<template>
  <div class="purchase-return-page">
    <el-container>
      <el-header height="auto">
        <el-card shadow="never">
          <el-form
            :inline="true"
            :model="formInline"
            label-width="auto"
            class="filter-form"
          >
            <el-form-item label="退货单号">
              <el-input
                v-model="formInline.goodsReturnsNo"
                clearable
                placeholder="请输入"
                style="width: 180px"
              />
            </el-form-item>
            <el-form-item label="单据状态">
              <el-select
                v-model="formInline.goodsReturnsStatus"
                placeholder="请选择"
                clearable
                style="width: 160px"
              >
                <el-option
                  v-for="item in PURCHASE_RETURN_STATUS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商">
              <el-select
                v-model="formInline.supplierId"
                placeholder="请选择"
                clearable
                style="width: 220px"
                filterable
                remote
                reserve-keyword
                :remote-method="handleSupplierSearch"
                :loading="supplierLoading"
                @visible-change="handleSupplierDropdownVisible"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.supplierId"
                  :label="item.supplierName"
                  :value="String(item.supplierId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="退货日期">
              <el-date-picker
                v-model="formInline.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
                style="width: 260px"
              />
            </el-form-item>
            <el-form-item>
              <el-space>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
                <el-button @click="advancedVisible = true">高级搜索</el-button>
              </el-space>
            </el-form-item>
          </el-form>
        </el-card>
      </el-header>
      <el-main>
        <el-card shadow="never">
          <div class="toolbar">
            <el-space wrap>
              <el-button type="success" size="small" @click="handleCreate">
                新增
              </el-button>
              <el-button size="small" @click="handleBatchDelete">
                删除
              </el-button>
              <el-button size="small" @click="handleCopy">
                复制
              </el-button>
              <el-button size="small" @click="handleAudit">
                审核
              </el-button>
              <el-button size="small" @click="handleRevoke">
                撤销
              </el-button>
              <el-button size="small" @click="handleClose">
                关闭
              </el-button>
              <el-button size="small" @click="handleOpen">
                开启
              </el-button>
              <el-button size="small" @click="handleExport">
                导出
              </el-button>
              <el-button size="small" @click="handleRefresh">
                刷新
              </el-button>
            </el-space>
          </div>

          <el-scrollbar x>
            <el-table
              ref="multipleTableRef"
              v-loading="loading"
              :data="tableData"
              row-key="goodsReturnsId"
              border
              stripe
              style="width: 100%"
              empty-text="暂无进货退货记录"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" fixed="left" />
              <el-table-column type="index" label="序号" width="60" fixed="left" />
              <el-table-column
                prop="goodsReturnsNo"
                label="退货单号"
                min-width="160"
                fixed="left"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  <el-link type="primary" @click="handleView(row)">
                    {{ row.goodsReturnsNo || '-' }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="goodsReturnsStatus" label="单据状态" width="110">
                <template #default="{ row }">
                  <el-tag :type="getStatusTagType(row.goodsReturnsStatus)" size="small">
                    {{ getStatusText(row.goodsReturnsStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="goodsReturnsDate" label="退货日期" width="130">
                <template #default="{ row }">
                  {{ formatDate(row.goodsReturnsDate) || '-' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="stockinGoodsNo"
                label="进货单号"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                prop="supplierName"
                label="供应商"
                min-width="160"
                show-overflow-tooltip
              />
              <el-table-column
                prop="goodsReturnsContact"
                label="联系人"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="goodsReturnsContactPhone"
                label="联系方式"
                width="140"
                show-overflow-tooltip
              />
              <el-table-column
                prop="goodsReturnsDepartment"
                label="进货部门"
                min-width="140"
                show-overflow-tooltip
              />
              <el-table-column
                prop="goodsReturnsUser"
                label="进货人"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="goodsReturnsQuantity"
                label="退货数量"
                width="110"
                align="right"
              >
                <template #default="{ row }">
                  {{ row.goodsReturnsQuantity ?? '-' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="goodsReturnsAmount"
                label="退货金额"
                width="130"
                align="right"
              >
                <template #default="{ row }">
                  <span class="amount-text">
                    ¥{{ formatAmount(row.goodsReturnsAmount) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="goodsReturnsGoodsList"
                label="退货货品"
                min-width="220"
                class-name="goods-column"
              >
                <template #default="{ row }">
                  <div class="goods-multi-text">
                    <template v-if="row.goodsReturnsGoodsList?.length">
                      <div
                        v-for="(name, idx) in row.goodsReturnsGoodsList"
                        :key="`${row.goodsReturnsId}-goods-${idx}`"
                        class="goods-name-item"
                      >
                        {{ name }}
                      </div>
                    </template>
                    <template v-else>
                      {{ row.goodsReturnsGoodsText || row.productNames || row.productName || '-' }}
                    </template>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="制单人"
                width="110"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.goodsReturnsUser || row.createor || '-' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="organizationName"
                label="所在部门"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column prop="goodsReturnsTime" label="制单时间" width="170">
                <template #default="{ row }">
                  {{ formatDateTime(row.goodsReturnsTime) || '-' }}
                </template>
              </el-table-column>
              <el-table-column
                label="审核人"
                width="110"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.goodsReturnsAuditor || currentUserName || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="createrTime" label="审核时间" width="170">
                <template #default="{ row }">
                  {{ formatDateTime(row.createrTime) || '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" width="150" align="center">
                <template #default="{ row }">
                  <el-button link type="primary" size="small" @click="handleEdit(row)">
                    编辑
                  </el-button>
                  <el-button link type="danger" size="small" @click="handleDelete(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </el-card>
        <el-card shadow="never" class="pagination-card">
          <div class="pagination-bar">
            <div class="pagination-info">
              共{{ page.listCount }}条， 每页{{ page.pagesize }}条， 当前第{{ page.pageindex }} /
              {{ page.pageCount || 1 }}页
            </div>
            <div class="pagination-controls">
              <el-button
                class="pagination-btn"
                link
                type="primary"
                size="small"
                @click="page.pageindex = 1"
              >
                首页
              </el-button>
              <el-pagination
                v-model:current-page="page.pageindex"
                v-model:page-size="page.pagesize"
                :page-sizes="[10, 20, 50, 100]"
                :total="page.listCount"
                prev-text="上一页"
                next-text="下一页"
                :background="true"
                layout="prev, pager, next"
              />
              <el-button
                class="pagination-btn"
                link
                type="primary"
                size="small"
                @click="page.pageindex = page.pageCount || 1"
              >
                尾页
              </el-button>
              <span class="pagination-jump">
                前往
                <el-input-number
                  v-model="page.pageindex"
                  :min="1"
                  :max="page.pageCount || 1"
                  size="small"
                  controls-position="right"
                  style="width: 90px"
                />
                页
              </span>
            </div>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <el-drawer v-model="advancedVisible" title="高级搜索" direction="rtl" size="520px">
      <el-form :model="advancedForm" label-width="100px" class="advanced-form">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="退货单号">
              <el-input v-model="advancedForm.goodsReturnsNo" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态">
              <el-select
                v-model="advancedForm.goodsReturnsStatusList"
                multiple
                clearable
                collapse-tags
                placeholder="请选择"
              >
                <el-option
                  v-for="item in PURCHASE_RETURN_STATUS"
                  :key="`adv-${item.value}`"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="供应商">
              <el-select
                v-model="advancedForm.supplierId"
                placeholder="请选择"
                clearable
                filterable
                remote
                reserve-keyword
                :remote-method="handleSupplierSearch"
                :loading="supplierLoading"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="`adv-supplier-${item.supplierId}`"
                  :label="item.supplierName"
                  :value="String(item.supplierId)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货日期">
              <el-date-picker
                v-model="advancedForm.goodsReturnsDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="退货货品">
              <el-input v-model="advancedForm.productName" clearable placeholder="货品名称/编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进货单号">
              <el-input v-model="advancedForm.stockinGoodsNo" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="进货部门">
              <el-input v-model="advancedForm.goodsReturnsDepartment" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进货人">
              <el-input v-model="advancedForm.goodsReturnsUser" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="advancedForm.goodsReturnsContact" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="advancedForm.goodsReturnsContactPhone" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="退货数量">
              <div class="range-input">
                <el-input-number v-model="advancedForm.goodsReturnsQuantityMin" :min="0" />
                <span class="range-separator">~</span>
                <el-input-number v-model="advancedForm.goodsReturnsQuantityMax" :min="0" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货金额">
              <div class="range-input">
                <el-input-number v-model="advancedForm.goodsReturnsAmountMin" :min="0" :precision="2" />
                <span class="range-separator">~</span>
                <el-input-number v-model="advancedForm.goodsReturnsAmountMax" :min="0" :precision="2" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="制单人">
              <el-input v-model="advancedForm.createor" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-input v-model="advancedForm.organizationName" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="advancedForm.goodsReturnsTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人">
              <el-input v-model="advancedForm.goodsReturnsAuditor" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="审核时间">
              <el-date-picker
                v-model="advancedForm.goodsReturnsAuditTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="handleAdvancedReset">重置</el-button>
          <el-button @click="advancedVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleAdvancedSearch">查询</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'
import moment from 'moment'
import router from '@/router'
import myaxios from '@/http/MyAxios'

interface GoodsReturnsItem {
  goodsReturnsId: string | number
  goodsReturnsNo: string
  goodsReturnsStatus: number | string
  goodsReturnsDate?: string
  stockinGoodsId?: string | number
  stockinGoodsNo?: string
  supplierId?: string | number
  supplierName?: string
  goodsReturnsContact?: string
  goodsReturnsContactPhone?: string
  organizationId?: string | number
  organizationName?: string
  userId?: string | number
  userName?: string
  goodsReturnsDepartment?: string
  goodsReturnsUser?: string
  goodsReturnsQuantity?: number
  goodsReturnsAmount?: number
  goodsReturnsReason?: string
  goodsReturnsRemark?: string
  goodsReturnsTime?: string
  goodsReturnsAuditor?: string
  createrTime?: string
  createor?: string
  goodsReturnsGoodsList?: string[]
  goodsReturnsGoodsText?: string
}

const PURCHASE_RETURN_STATUS = [
  { value: 0, label: '草稿', tagType: 'info' },
  { value: 1, label: '待审核', tagType: 'warning' },
  { value: 2, label: '驳回', tagType: 'danger' },
  { value: 3, label: '未出库', tagType: 'info' },
  { value: 4, label: '部分出库', tagType: 'warning' },
  { value: 5, label: '已完成', tagType: 'success' },
  { value: 6, label: '已关闭', tagType: 'danger' },
]

const STOCKIN_STATUS_MAP = [
  { value: 0, label: '草稿', tagType: 'info' },
  { value: 1, label: '待审核', tagType: 'warning' },
  { value: 2, label: '驳回', tagType: 'danger' },
  { value: 3, label: '未出库', tagType: 'info' },
  { value: 4, label: '部分出库', tagType: 'warning' },
  { value: 5, label: '已入库', tagType: 'success' },
  { value: 6, label: '已关闭', tagType: 'danger' },
  { value: 7, label: '作废', tagType: 'danger' },
]

const loading = ref(false)
const advancedVisible = ref(false)
const tableData = ref<GoodsReturnsItem[]>([])
const currentUserName = ref('')
const supplierOptions = ref<any[]>([])
const supplierLoading = ref(false)
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<GoodsReturnsItem[]>([])

const formInline = reactive({
  goodsReturnsNo: '',
  goodsReturnsStatus: '',
  supplierId: '',
  dateRange: [] as string[],
})

const advancedForm = reactive({
  goodsReturnsNo: '',
  goodsReturnsStatusList: [] as Array<number | string>,
  supplierId: '',
  goodsReturnsDateRange: [] as string[],
  productName: '',
  stockinGoodsNo: '',
  goodsReturnsDepartment: '',
  goodsReturnsUser: '',
  goodsReturnsContact: '',
  goodsReturnsContactPhone: '',
  goodsReturnsQuantityMin: undefined as number | undefined,
  goodsReturnsQuantityMax: undefined as number | undefined,
  goodsReturnsAmountMin: undefined as number | undefined,
  goodsReturnsAmountMax: undefined as number | undefined,
  createor: '',
  organizationName: '',
  goodsReturnsTimeRange: [] as string[],
  goodsReturnsAuditor: '',
  goodsReturnsAuditTimeRange: [] as string[],
})

const page = reactive({
  pageindex: 1,
  pagesize: 10,
  listCount: 0,
  pageCount: 0,
})

const pickFirst = <T = any>(
  source: Record<string, any>,
  keys: string[],
  fallback: T | undefined = undefined,
): T | undefined => {
  for (const key of keys) {
    const value = source?.[key]
    if (value !== undefined && value !== null && value !== '') {
      return value as T
    }
  }
  return fallback
}

const safeToNumber = (value: any): number | undefined => {
  if (value === undefined || value === null || value === '') return undefined
  const num = Number(value)
  return Number.isNaN(num) ? undefined : num
}

const splitGoodsFromString = (value: string): string[] => {
  if (!value) return []
  return value
    .replace(/[\[\]{}"]/g, '')
    .split(/[,，、;；\n\r]+/)
    .map((item) => item.trim())
    .filter(Boolean)
}

const extractReturnGoods = (row: Record<string, any>): string[] => {
  const candidates = [
    row.goodsReturnsGoodsList,
    row.goodsDetails,
    row.returnGoodsList,
    row.returnGoods,
    row.goodsNames,
    row.productNames,
    row.goodsList,
    row.products,
    row.details,
    row.returnDetails,
    row.items,
  ]

  const result: string[] = []
  const collect = (text?: string) => {
    if (!text) return
    const trimmed = text.trim()
    if (trimmed && !result.includes(trimmed)) {
      result.push(trimmed)
    }
  }

  for (const candidate of candidates) {
    if (!candidate && candidate !== 0) continue
    if (Array.isArray(candidate)) {
      candidate.forEach((item, idx) => {
        if (typeof item === 'string') {
          splitGoodsFromString(item).forEach(collect)
        } else if (item) {
          const label =
            item.productName ||
            item.goodsName ||
            item.name ||
            item.productCode ||
            item.goodsCode ||
            ''
          const spec =
            item.specification ||
            item.specificationModel ||
            item.unitName ||
            item.unit ||
            ''
          const qty =
            item.quantity ??
            item.returnQuantity ??
            item.qty ??
            item.count
          const detailParts = []
          if (spec) detailParts.push(spec)
          if (typeof qty === 'number' && Number.isFinite(qty)) detailParts.push(`×${qty}`)
          const detail = detailParts.length ? `（${detailParts.join(' / ')}）` : ''
          collect(label ? `${idx + 1}. ${label}${detail}` : '')
        }
      })
      continue
    }
    if (typeof candidate === 'string') {
      splitGoodsFromString(candidate).forEach(collect)
      continue
    }
    if (typeof candidate === 'object') {
      const nested =
        candidate?.data ||
        candidate?.list ||
        candidate?.records ||
        candidate?.items
      if (Array.isArray(nested)) {
        nested.forEach((item) => {
          if (typeof item === 'string') {
            splitGoodsFromString(item).forEach(collect)
          } else if (item) {
            collect(item.productName || item.goodsName || item.name)
          }
        })
      }
    }
  }

  return result
}

const normalizeReturnRows = (rows: any[]): GoodsReturnsItem[] => {
  return rows.map((item, index) => {
    const goodsList = extractReturnGoods(item)
    const goodsReturnsId =
      pickFirst(item, ['goodsReturnsId', 'purchaseReturnId', 'returnOrderId', 'goodsReturnId', 'returnId', 'id']) ??
      pickFirst(item, ['goodsReturnsNo', 'purchaseReturnNo', 'returnOrderNo', 'goodsReturnCode', 'returnCode', 'documentNo']) ??
      `goods-return-${index}`
    return {
      goodsReturnsId,
      goodsReturnsNo:
        pickFirst(item, ['goodsReturnsNo', 'purchaseReturnNo', 'returnOrderNo', 'goodsReturnCode', 'returnCode', 'documentNo'], '-') ??
        '-',
      goodsReturnsStatus: pickFirst(item, ['goodsReturnsStatus', 'status', 'returnStatus', 'documentStatus', 'state'], 0) ?? 0,
      goodsReturnsDate: pickFirst(item, ['goodsReturnsDate', 'returnDate', 'documentDate', 'goodsReturnDate']),
      stockinGoodsId: pickFirst(item, ['stockinGoodsId', 'stockinId', 'stockInId']),
      stockinGoodsNo: pickFirst(item, ['stockinGoodsNo', 'stockinOrderNo', 'purchaseOrderNo', 'sourceOrderNo', 'sourceCode'], '-'),
      supplierName: pickFirst(item, ['supplierName', 'vendorName', 'partnerName']),
      supplierId: pickFirst(item, ['supplierId', 'vendorId']),
      goodsReturnsContact: pickFirst(item, ['goodsReturnsContact', 'contactName', 'linkMan', 'linkman', 'contacts']),
      goodsReturnsContactPhone: pickFirst(item, ['goodsReturnsContactPhone', 'contactPhone', 'phone', 'linkPhone', 'mobile']),
      organizationId: pickFirst(item, ['organizationId', 'departmentId']),
      organizationName: pickFirst(item, ['organizationName', 'departmentName', 'makerDepartment', 'purchaseDepartment', 'goodsReturnsDepartment']),
      userId: pickFirst(item, ['userId', 'handlerId']),
      userName: pickFirst(item, ['userName', 'handler']),
      goodsReturnsDepartment: pickFirst(item, ['goodsReturnsDepartment', 'purchaseDepartment', 'departmentName']),
      goodsReturnsUser: pickFirst(item, ['goodsReturnsUser', 'purchaseUser', 'buyerName', 'handler']),
      goodsReturnsQuantity:
        safeToNumber(
          pickFirst(item, ['goodsReturnsQuantity', 'returnQuantity', 'quantity', 'qty', 'returnCount', 'goodsQty']),
        ) ?? undefined,
      goodsReturnsAmount:
        safeToNumber(
          pickFirst(item, ['goodsReturnsAmount', 'returnAmount', 'amount', 'money', 'totalAmount', 'returnMoney']),
        ) ?? undefined,
      goodsReturnsReason: pickFirst(item, ['goodsReturnsReason', 'returnReason', 'reason']),
      goodsReturnsRemark: pickFirst(item, ['goodsReturnsRemark', 'remark', 'memo', 'note']),
      goodsReturnsTime: pickFirst(item, ['goodsReturnsTime', 'createTime', 'documentTime', 'makerTime']),
      goodsReturnsAuditor: pickFirst(item, ['goodsReturnsAuditor', 'auditor', 'approveUser', 'reviewer']),
      createrTime: pickFirst(item, ['createrTime', 'auditTime', 'approveTime', 'reviewTime']),
      createor: pickFirst(item, ['createor', 'creator', 'createUser', 'documentMaker', 'makerName']),
      goodsReturnsGoodsList: goodsList,
      goodsReturnsGoodsText:
        goodsList.length
          ? goodsList.join('，')
          : pickFirst(item, [
              'goodsReturnsGoodsText',
              'goodsDetailsText',
              'goodsReturnsGoods',
              'goodsReturnsGoodsName',
              'productNames',
              'productDisplayText',
              'productName',
            ]) || '',
    }
  })
}

const fetchReturnList = async () => {
  loading.value = true
  try {
    const params = {
      goodsReturnsNo: advancedForm.goodsReturnsNo || formInline.goodsReturnsNo,
      goodsReturnsStatus:
        advancedForm.goodsReturnsStatusList.length > 0
          ? advancedForm.goodsReturnsStatusList.join(',')
          : formInline.goodsReturnsStatus,
      supplierId: advancedForm.supplierId || formInline.supplierId,
      beginDate: advancedForm.goodsReturnsDateRange?.[0] || formInline.dateRange?.[0] || '',
      endDate: advancedForm.goodsReturnsDateRange?.[1] || formInline.dateRange?.[1] || '',
      stockinGoodsNo: advancedForm.stockinGoodsNo,
      productName: advancedForm.productName,
      goodsReturnsDepartment: advancedForm.goodsReturnsDepartment,
      goodsReturnsUser: advancedForm.goodsReturnsUser,
      goodsReturnsContact: advancedForm.goodsReturnsContact,
      goodsReturnsContactPhone: advancedForm.goodsReturnsContactPhone,
      goodsReturnsQuantityMin: advancedForm.goodsReturnsQuantityMin,
      goodsReturnsQuantityMax: advancedForm.goodsReturnsQuantityMax,
      goodsReturnsAmountMin: advancedForm.goodsReturnsAmountMin,
      goodsReturnsAmountMax: advancedForm.goodsReturnsAmountMax,
      createor: advancedForm.createor,
      organizationName: advancedForm.organizationName,
      goodsReturnsAuditor: advancedForm.goodsReturnsAuditor,
      goodsReturnsTimeBegin: advancedForm.goodsReturnsTimeRange?.[0] || '',
      goodsReturnsTimeEnd: advancedForm.goodsReturnsTimeRange?.[1] || '',
      goodsReturnsAuditTimeBegin: advancedForm.goodsReturnsAuditTimeRange?.[0] || '',
      goodsReturnsAuditTimeEnd: advancedForm.goodsReturnsAuditTimeRange?.[1] || '',
      pageindex: page.pageindex,
      pagesize: page.pagesize,
    }

    const res = await myaxios.get('/api/GoodsReturns/GetGoodsReturns', {
      params,
    })
    const result = res.data || {}
    if (result.code === 200) {
      const dataSection =
        result.data?.data ??
        result.data?.records ??
        result.data?.list ??
        result.data ??
        []
      const rows = Array.isArray(dataSection) ? dataSection : dataSection?.data ?? []
      tableData.value = normalizeReturnRows(rows || [])
      page.listCount = result.data?.listCount ?? result.data?.total ?? rows.length ?? 0
      page.pageCount =
        result.data?.pageCount ??
        (page.pagesize ? Math.ceil(page.listCount / page.pagesize) : 0)
    } else {
      tableData.value = []
      ElMessage.error(result.message || '获取进货退货列表失败')
    }
  } catch (error) {
    console.error('获取进货退货列表失败:', error)
    tableData.value = []
    ElMessage.error('获取进货退货列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const loadSuppliers = async (keyword = '') => {
  if (supplierLoading.value) return
  supplierLoading.value = true
  try {
    const res = await myaxios.get('/api/Supplier/GetSupplier', {
      params: {
        pageindex: 1,
        pagesize: 50,
        supplierName: keyword,
      },
    })
    if (res.data?.code === 200) {
      supplierOptions.value = res.data?.data?.data || []
    }
  } catch (error) {
    console.error('获取供应商失败:', error)
  } finally {
    supplierLoading.value = false
  }
}

const loadCurrentUserName = async () => {
  try {
    const res = await myaxios.get('/api/User/GetMyProfile')
    const data = res?.data?.data || {}
    currentUserName.value =
      data.userName ||
      data.realName ||
      data.nickname ||
      localStorage.getItem('username') ||
      ''
    if (currentUserName.value) {
      localStorage.setItem('username', currentUserName.value)
    }
  } catch (error) {
    currentUserName.value = localStorage.getItem('username') || ''
  }
}

const handleSupplierSearch = (keyword: string) => {
  loadSuppliers(keyword)
}

const handleSupplierDropdownVisible = (visible: boolean) => {
  if (visible && !supplierOptions.value.length) {
    loadSuppliers()
  }
}

const handleQuery = () => {
  page.pageindex = 1
  fetchReturnList()
}

const handleReset = () => {
  formInline.goodsReturnsNo = ''
  formInline.goodsReturnsStatus = ''
  formInline.supplierId = ''
  formInline.dateRange = []
  page.pageindex = 1
  fetchReturnList()
}

const handleAdvancedReset = () => {
  advancedForm.goodsReturnsNo = ''
  advancedForm.goodsReturnsStatusList = []
  advancedForm.supplierId = ''
  advancedForm.goodsReturnsDateRange = []
  advancedForm.productName = ''
  advancedForm.stockinGoodsNo = ''
  advancedForm.goodsReturnsDepartment = ''
  advancedForm.goodsReturnsUser = ''
  advancedForm.goodsReturnsContact = ''
  advancedForm.goodsReturnsContactPhone = ''
  advancedForm.goodsReturnsQuantityMin = undefined
  advancedForm.goodsReturnsQuantityMax = undefined
  advancedForm.goodsReturnsAmountMin = undefined
  advancedForm.goodsReturnsAmountMax = undefined
  advancedForm.createor = ''
  advancedForm.organizationName = ''
  advancedForm.goodsReturnsTimeRange = []
  advancedForm.goodsReturnsAuditor = ''
  advancedForm.goodsReturnsAuditTimeRange = []
}

const handleAdvancedSearch = () => {
  page.pageindex = 1
  advancedVisible.value = false
  fetchReturnList()
}

const handleSelectionChange = (val: GoodsReturnsItem[]) => {
  multipleSelection.value = val
}

watch(
  () => [page.pageindex, page.pagesize],
  () => {
    fetchReturnList()
  },
)

const handleCreate = () => {
  router.push('/creategoodsreturn')
}

const handleEdit = (row: GoodsReturnsItem) => {
  router.push({
    path: '/updategoodsreturn',
    query: { goodsReturnsId: row.goodsReturnsId },
  })
}

const handleView = (row: GoodsReturnsItem) => {
  router.push({
    path: '/detailgoodsreturn',
    query: { goodsReturnsId: row.goodsReturnsId },
  })
}

const handleDelete = (row: GoodsReturnsItem) => {
  ElMessageBox.confirm('确认删除该退货单吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await myaxios.delete('/api/GoodsReturns/DeleteGoodsReturns', {
          params: { goodsReturnsId: row.goodsReturnsId },
        })
        if (res.data?.code === 200) {
          ElMessage.success(res.data?.message || '删除成功')
          fetchReturnList()
        } else {
          ElMessage.error(res.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除退货单失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择需要删除的退货单')
    return
  }
  ElMessageBox.confirm(`确认删除选中的${multipleSelection.value.length}条退货单吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const ids = multipleSelection.value.map((item) => item.goodsReturnsId)
        const res = await myaxios.delete('/api/GoodsReturns/BatchDeleteGoodsReturns', {
          params: { ids: ids.join(',') },
        })
        if (res.data?.code === 200) {
          ElMessage.success(res.data?.message || '批量删除成功')
          multipleSelection.value = []
          fetchReturnList()
        } else {
          ElMessage.error(res.data?.message || '批量删除失败')
        }
      } catch (error) {
        console.error('批量删除退货单失败:', error)
        ElMessage.error('批量删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handleAudit = () => {
  ElMessage.warning('审核功能正在开发中')
}

const handleRevoke = () => {
  ElMessage.warning('撤销功能正在开发中')
}

const handleClose = () => {
  ElMessage.warning('关闭功能正在开发中')
}

const handleOpen = () => {
  ElMessage.warning('开启功能正在开发中')
}

const handleCopy = () => {
  ElMessage.warning('复制功能正在开发中')
}

const handleExport = async () => {
  try {
    const params: Record<string, any> = {
      goodsReturnsNo: formInline.goodsReturnsNo,
      goodsReturnsStatus: formInline.goodsReturnsStatus,
      supplierId: formInline.supplierId,
      beginDate: formInline.dateRange?.[0] || '',
      endDate: formInline.dateRange?.[1] || '',
      pageindex: 1,
      pagesize: 10000,
    }
    // 添加高级搜索条件
    if (advancedForm.goodsReturnsNo) params.goodsReturnsNo = advancedForm.goodsReturnsNo
    if (advancedForm.goodsReturnsStatusList?.length) {
      params.goodsReturnsStatus = advancedForm.goodsReturnsStatusList.join(',')
    }
    if (advancedForm.supplierId) params.supplierId = advancedForm.supplierId
    if (advancedForm.goodsReturnsDateRange?.length) {
      params.beginDate = advancedForm.goodsReturnsDateRange[0]
      params.endDate = advancedForm.goodsReturnsDateRange[1]
    }
    if (advancedForm.productName) params.productName = advancedForm.productName
    if (advancedForm.stockinGoodsNo) params.stockinGoodsNo = advancedForm.stockinGoodsNo
    if (advancedForm.goodsReturnsDepartment) params.goodsReturnsDepartment = advancedForm.goodsReturnsDepartment
    if (advancedForm.goodsReturnsUser) params.goodsReturnsUser = advancedForm.goodsReturnsUser
    if (advancedForm.goodsReturnsContact) params.goodsReturnsContact = advancedForm.goodsReturnsContact
    if (advancedForm.goodsReturnsContactPhone) params.goodsReturnsContactPhone = advancedForm.goodsReturnsContactPhone
    if (advancedForm.goodsReturnsQuantityMin !== undefined) params.goodsReturnsQuantityMin = advancedForm.goodsReturnsQuantityMin
    if (advancedForm.goodsReturnsQuantityMax !== undefined) params.goodsReturnsQuantityMax = advancedForm.goodsReturnsQuantityMax
    if (advancedForm.goodsReturnsAmountMin !== undefined) params.goodsReturnsAmountMin = advancedForm.goodsReturnsAmountMin
    if (advancedForm.goodsReturnsAmountMax !== undefined) params.goodsReturnsAmountMax = advancedForm.goodsReturnsAmountMax
    if (advancedForm.createor) params.createor = advancedForm.createor
    if (advancedForm.organizationName) params.organizationName = advancedForm.organizationName
    if (advancedForm.goodsReturnsAuditor) params.goodsReturnsAuditor = advancedForm.goodsReturnsAuditor
    if (advancedForm.goodsReturnsTimeRange?.length) {
      params.goodsReturnsTimeBegin = advancedForm.goodsReturnsTimeRange[0]
      params.goodsReturnsTimeEnd = advancedForm.goodsReturnsTimeRange[1]
    }
    if (advancedForm.goodsReturnsAuditTimeRange?.length) {
      params.goodsReturnsAuditTimeBegin = advancedForm.goodsReturnsAuditTimeRange[0]
      params.goodsReturnsAuditTimeEnd = advancedForm.goodsReturnsAuditTimeRange[1]
    }
    // 如果有选中的记录，只导出选中的
    if (multipleSelection.value.length) {
      const ids = multipleSelection.value.map((item) => item.goodsReturnsId)
      params.goodsReturnsIds = ids.join(',')
    }
    const res = await myaxios.get('/api/GoodsReturns/ExportGoodsReturnsExcel', {
      params,
      responseType: 'blob',
    })
    // 创建下载链接
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `进货退货列表_${moment().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

const handleRefresh = () => {
  multipleTableRef.value?.clearSelection?.()
  multipleSelection.value = []
  fetchReturnList()
  ElMessage.success('已刷新进货退货列表')
}

const formatDate = (date?: string) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

const formatAmount = (amount?: number) => {
  if (amount === undefined || amount === null || Number.isNaN(Number(amount))) return '0.00'
  return Number(amount).toFixed(2)
}

const getStatusOption = (status: number | string) => {
  const statusNumber = Number(status)
  return PURCHASE_RETURN_STATUS.find((item) => Number(item.value) === statusNumber)
}

const getStatusText = (status: number | string) => {
  return getStatusOption(status)?.label ?? '未知'
}

const getStatusTagType = (status: number | string) => {
  return getStatusOption(status)?.tagType ?? 'info'
}

onMounted(() => {
  fetchReturnList()
  loadSuppliers()
  loadCurrentUserName()
})
</script>

<style scoped>
.purchase-return-page {
  padding: 12px;
  background: #f5f7fa;
  min-height: 100vh;
}

.toolbar {
  margin-bottom: 12px;
}

.pagination-card {
  margin-top: 16px;
}

.pagination-bar {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.pagination-info {
  font-size: 12px;
  color: #666;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-jump {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.pagination-btn :deep(span) {
  padding: 0 10px;
}

.range-input {
  display: flex;
  align-items: center;
  gap: 4px;
  width: 100%;
}

.range-input :deep(.el-input-number) {
  flex: 1;
}

.range-separator {
  font-size: 12px;
  color: #666;
}

.advanced-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.goods-column :deep(.cell) {
  white-space: normal !important;
  word-break: break-word;
}

.goods-multi-text {
  white-space: normal;
  word-break: break-word;
}

.goods-name-item {
  line-height: 20px;
}

.amount-text {
  font-weight: 500;
  color: #f56c6c;
  font-family: 'Courier New', monospace;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 12px;
}
</style>

